package com.qingzhuge.manager.security.support;

import com.qingzhuge.manager.dto.AdminLoginDto;
import com.qingzhuge.manager.dto.SecurityUser;
import com.qingzhuge.manager.entity.SysUser;
import com.qingzhuge.manager.security.token.UsernameAuthenticationToken;
import com.qingzhuge.manager.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author zeroxiao
 * @date 2019/9/12 17:18
 * @description
 */
@Slf4j
@Component
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private ISysUserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernameAuthenticationToken token = (UsernameAuthenticationToken) authentication;
        String username = (token.getPrincipal() == null) ? "NONE_PROVIDED" : token.getName();
        String password = token.getCredentials();
        if (StringUtils.isEmpty(password)) {
            log.debug("密码不能为空");
            throw new BadCredentialsException("密码不能为空");
        }
        AdminLoginDto dto = new AdminLoginDto();
        dto.setUsername(username);
        dto.setPassword(password);
        dto.setCaptcha(token.getCode());
        SysUser user = userService.login(dto);
        if (user == null) {
            if (log.isDebugEnabled()) {
                log.debug("账号不存在:[{}]",username);
            }
            throw new UsernameNotFoundException("用户不存在");
        }
        log.debug("用户登录:[{}]",username);
        String userPassword = user.getPassword();
        if (!userService.matchesPassword(password,userPassword)) {
            if (log.isDebugEnabled()) {
                log.debug("账号或密码不正确:[{}]",password);
            }
            throw new BadCredentialsException("账号或密码不正确");
        }
        log.debug("用户登录,密码验证完成:[{}]",username);
        SecurityUser userDetails = userService.createUserDetails(user);
        UsernameAuthenticationToken authenticationToken = new UsernameAuthenticationToken(userDetails, password,token.getCode(), userDetails.getAuthorities());
        authenticationToken.setDetails(token.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernameAuthenticationToken.class.isAssignableFrom(authentication));
    }
}